﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using CVSA.Suporte.Sinacor.BMFBovespa.Negocio;
using CVSA.Suporte.Sinacor.BMFBovespa.Entidades;
using System.Timers;
using System.IO;
using System.Configuration; 

namespace RemedySynchService
{
    public partial class Synch : ServiceBase
    {
        
        public System.Timers.Timer aTimer = new System.Timers.Timer();
        public System.Timers.Timer aTimer2 = new System.Timers.Timer();

        public Synch()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            aTimer = new System.Timers.Timer();
            aTimer2 = new System.Timers.Timer();
            aTimer2.Interval = 43200000;
            aTimer.Interval = Convert.ToInt32(ConfigurationManager.AppSettings["intervalServico"]);
            aTimer.Elapsed += new ElapsedEventHandler(aTimer_Elapsed);
            aTimer2.Elapsed += new ElapsedEventHandler(aTimer2_Elapsed);
            aTimer.Enabled = true;

        }

        void aTimer2_Elapsed(object sender, ElapsedEventArgs e)
        {
            Remedy remedy = new Remedy();
            CVSA.Suporte.Sinacor.BMFBovespa.Negocio.SRM srm = new CVSA.Suporte.Sinacor.BMFBovespa.Negocio.SRM();
            try
            {
                DataTable odtchamados = remedy.ObterDadosOciosos();
                remedy.AtualizarChamadosOciosos(odtchamados);
                odtchamados.Dispose();
                
            }
            catch (Exception ex)
            {
                aTimer2.Stop();
                EventLog.WriteEntry("Erro Remedy Synch (Atualizar Geral) : " + ex.Message, EventLogEntryType.Error); 
                aTimer2.Start();
            }
            finally
            {
                remedy = null;
            }
        }

        void aTimer_Elapsed(object sender, ElapsedEventArgs e)
        {

             SynchRemedy();
        }

        private void SynchRemedy()
        {
            Remedy remedy = new Remedy();
            List<Chamado> chamados = new List<Chamado>();
            try
            {

                chamados = remedy.ObterDados(string.Empty, string.Empty);
                remedy.Sincronizar(chamados);
            }
            catch (Exception ex)
            {
                aTimer.Stop();
                EventLog.WriteEntry("Erro Remedy Synch : " + ex.Message, EventLogEntryType.Error);
                aTimer.Start();
            }

            finally
            {
                remedy = null;
                chamados = null;
            }
        }
        
    }
}
